﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;

using MapCenterSystem.DataInfo;

namespace MapCenterSystem.ServiceProvider.LocalMap
{
    public class LocalMapProviderEx: LocalMapProvider
    {
        private Image[,] image = new Image[3, 3];
        public Image GetMapImage(MapInfoEx map)
        {
            map.MapStore = Path.Combine(map.MapStore, "Local");
            InitListImage(map);
            Image memImage = CombineImage();
            Image currentImage = new Bitmap(map.Size.Width, map.Size.Height);
            Graphics g = Graphics.FromImage(currentImage);
            int k = map.MapCenter.X % 256;
            int t = map.MapCenter.Y % 256;
            int temp1 = 256 + k - currentImage.Width / 2;
            int temp2 = 256 + t - currentImage.Height / 2;
            g.DrawImage(memImage, new Rectangle(0, 0, currentImage.Width, currentImage.Height),
                new Rectangle(temp1, temp2, currentImage.Width, currentImage.Height), GraphicsUnit.Pixel);
            g.Dispose();

            return currentImage;
        }

        public void InitListImage(MapInfoEx map)
        {
            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    Point currentTile = new Point(map.Tile.X + i - 1, map.Tile.Y + j - 1);
                    MapInfoEx mapTemp = new MapInfoEx();
                    mapTemp.MapStore = map.MapStore;
                    mapTemp.Size = map.Size;
                    mapTemp.MapSource = map.MapSource;
                    mapTemp.Zoom = map.Zoom;
                    mapTemp.Tile = currentTile;
                    image[i, j] = new Bitmap(mapTemp.GetFullPath());
                }
            }
        }

        private Image CombineImage()
        {
            Image memImage = new Bitmap(3 * 256, 3 * 256);
            Graphics g = Graphics.FromImage(memImage);
            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    g.DrawImage(image[i, j], i * 256, j * 256);
                }
            }
            g.Dispose();
            return memImage;
        }
    }
}
